import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int findMaxLength1(int[] nums) {
        Map<Integer,Integer> hashmap = new HashMap<>();
        hashmap.put(0,-1);
        int sum = 0;
        int ret = 0;
        for(int i = 0; i < nums.length; i++) {
            sum += (nums[i] == 0 ? -1 : 1);
            if(hashmap.containsKey(sum)) {
                ret = Math.max(ret,i - hashmap.get(sum));
            } else {
                hashmap.put(sum,i);
            }
        }
        return ret;
    }
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
        hash.put(0, -1); // 默认存在⼀个前缀和为 0 的情况
        int sum = 0;
        int ret = 0;
        for(int i = 0; i < nums.length; i++)
        {
            sum += (nums[i] == 0 ? -1 : 1); // 计算当前位置的前缀和
            if(hash.containsKey(sum)) ret = Math.max(ret, i - hash.get(sum));
            else hash.put(sum, i);
        }
        return ret;
    }
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length, n = mat[0].length;
        // 1. 预处理前缀和矩阵
        int[][] dp = new int[m + 1][n + 1];
        for(int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }
        // 2. 使⽤
        int[][] ret = new int[m][n];
        for(int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int x1 = Math.max(0, i - k) + 1;
                int y1 = Math.max(0, j - k) + 1;
                int x2 = Math.min(m - 1, i + k) + 1;
                int y2 = Math.min(n - 1, j + k) + 1;
                ret[i][j] = dp[x2][y2] - dp[x1 - 1][y2] - dp[x2][y1 - 1] + dp[x1 - 1][y1 - 1];
            }
        }
        return ret;
    }
}
